package com.cn.appcore.http

import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File

/**
 * 项目：MyCustLib
 * 包名：com.cxz.kotlin.mvvm.http
 * 类名：TypeConversion
 * 创建时间：6/3/21 11:45 AM
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
object TypeConversion {

//    fun httpRequestBody(json: Any?): RequestBody {
//        return when (json) {
//            is String -> json.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
//            is File -> RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)
//            is ByteString -> RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)
//            is ByteArray -> RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)
//            else -> RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JsonUtils.toJson(json))
//        }
//    }

    /**
     * 转json
     */
    fun httpRequestBody(json: String): RequestBody {
        return json.toRequestBody("application/json".toMediaTypeOrNull())
    }


    /**
     * 上传文件
     */
    fun multipartBodyPartFile(fileStr: String): MultipartBody.Part {
        val file = File(fileStr)
        val requestBody = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
        return MultipartBody.Part.createFormData("file", file.name, requestBody)


    }

    /**
     * 上传文件
     */
    fun multipartBodyPartVideoFile(fileStr: String): MultipartBody.Part {
//        val file = File(fileStr)
//        val requestBody = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
//        return MultipartBody.Part.createFormData("file", file.name, requestBody)

        val file = File(fileStr)
        val requestBody = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file)
        return MultipartBody.Part.createFormData("file", file.name, requestBody)
    }
}